package engine;


import java.awt.*;
import java.util.*;
import java.util.List;

/**
 * This class contain information about all
 * external conditions of environment
 */
public class Cell {

    public static final int CELL_SIZE = 10000;

    private final int xPosition;
    private final int yPosition;

    public final World myWorld;
    public final List<Creature> creaturesOfCell;

    public Color color;

    public boolean grassEnough;
    public int grassPortion;
    private int population = 0;

    private int grass = 500;
    private int futureGrass = 1000;

    public Cell(int x, int y, Color color, World world) {
        xPosition = x;
        yPosition = y;
        this.color = color;
        creaturesOfCell = new ArrayList<>();
        this.myWorld = world;
    }

    public void setGrass(int grass) {
        this.grass = grass;
    }

    public void setFutureGrass(int futureGrass) {
        this.futureGrass = futureGrass;
    }

    public int getGrass() {

        return grass;
    }

    public int getFutureGrass() {
        return futureGrass;
    }

    public int getXPosition() {
        return xPosition;
    }

    public int getYPosition() {
        return yPosition;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public String toString() {
        return "" + xPosition + "x" + yPosition + " (" + creaturesOfCell.size() + ")";
    }

    public void cellDay() {
        Map<Creature, Decision> decisions = new HashMap<>(creaturesOfCell.size());
        grass = futureGrass;
        for (Creature currentCreature : creaturesOfCell) {
            decisions.put(currentCreature, currentCreature.dayDecision());
        }

        List<Creature> grassWantedCreatures = new ArrayList<>();
        decisions.forEach((p, v) -> {
            if (v == Decision.eatGrass) {
                grassWantedCreatures.add(p);
            }
        });

        int grassNeeded = grassWantedCreatures.stream()
                .mapToInt((p) -> p.getHunger())
                .sum();
        grassEnough = (grassNeeded < grass);
        grassPortion = (grassWantedCreatures.isEmpty()) ? 0 : grass / grassWantedCreatures.size();

        decisions.forEach((p, v) -> {
            if (p.isAlive) {
                p.dayAction(v);
            }
        });

        // Must be at Day class
        for (ListIterator<Creature> i = creaturesOfCell.listIterator(); i.hasNext(); ) {
            Creature p = i.next();
            p.rest(p.decision == Decision.stay);
            p.increaseAge();

            if (p.getHunger() >= p.getWidth()) {
                i.remove();
                p.die("hunger");
            }
        }
    }




}
